package com.tn.openrpc.jms.spring;

import java.util.List;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;

import com.tn.openrpc.util.FactoryException;
import com.tn.openrpc.util.ParametrizedFactory;

/**
 * An implementation of <code>ParametrizedFactory</code> that delegates to a <code>BeanFactory</code> returning the a
 * bean with a name matching the parameter.
 */
public class SpringTargetFactory implements BeanFactoryAware, ParametrizedFactory<Object, String>
{
  private BeanFactory beanFactory;
  private List<String> accessibleBeans;

  /**
   * {@inheritDoc}
   */
  @Override
  public void setBeanFactory(BeanFactory beanFactory) throws BeansException
  {
    this.beanFactory = beanFactory;
  }

  /**
   * Sets the accessible beans.  Be default this list is empty meaning all beans can be accessed.
   */
  public void setAccessibleBeans(List<String> accessibleBeans)
  {
    this.accessibleBeans = accessibleBeans;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public Object newInstance(String beanId) throws FactoryException
  {
    if (!accessibleBeans.isEmpty() && accessibleBeans.contains(beanId))
    {
      throw new FactoryException("Bean not accessible: " + beanId);
    }

    Object bean = beanFactory.getBean(beanId);

    if (bean == null)
    {
      throw new FactoryException("Could not find bean with id: " + beanId);
    }

    return bean;
  }
}
